package com.mysiteforme.admin.controller.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.entity.VO.UserExamDto;
import com.mysiteforme.admin.entity.user.*;
import com.mysiteforme.admin.realm.AuthRealm;
import com.mysiteforme.admin.service.question.ChUserExamService;
import com.mysiteforme.admin.service.user.ChClassService;
import com.mysiteforme.admin.service.user.ChStudyVideoRecordService;
import com.mysiteforme.admin.service.user.ChTaskService;
import com.mysiteforme.admin.service.user.ChUserLinkTaskService;
import com.mysiteforme.admin.util.DateUtil;
import com.mysiteforme.admin.util.IdWorker;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习任务接口
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/chTask")
public class ChTaskController {

    @Autowired
    private ChTaskService chTaskService;

    @Autowired
    private ChClassService chClassService;

    @Autowired
    private ChStudyVideoRecordService chStudyVideoRecordService;

    @Autowired
    private ChUserExamService chUserExamService;

    @Autowired
    private ChUserLinkTaskService chUserLinkTaskService;


    @GetMapping("/list")
    @SysLog("跳转列表")
    public String list() {
        return "/ytzluser/chTask/list";
    }

    @PostMapping("/list")
    @ResponseBody
    @SysLog("请求列表数据")
    public LayerData<ChTask> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                  @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                  @RequestParam(value = "condition", required = false) String condition,
                                  @RequestParam(value = "taskType", required = false) String taskType,
                                  @RequestParam(value = "taskStatus", required = false) String taskStatus,
                                  @RequestParam(value = "classId", required = false) String classId) {
        LayerData<ChTask> layerData = new LayerData<>();
        EntityWrapper<ChTask> entityWrapper = new EntityWrapper<>();
        entityWrapper.isWhere(true);
        if (StringUtils.isNotEmpty(condition)) {
            entityWrapper.like("real_name", "%" + condition + "%");
        }
        if (StringUtils.isNotEmpty(taskType) && !taskType.equals("0")) {
            entityWrapper.andNew().eq("task_type", taskType);
        }
        if (StringUtils.isNotEmpty(taskStatus) && !taskType.equals("0")) {
            entityWrapper.andNew().eq("task_status", taskStatus);
        }
        if (StringUtils.isNotEmpty(classId) && !taskType.equals("0")) {
            entityWrapper.andNew().eq("u.class_id", classId);
        }
        Page<ChTask> pageData = chTaskService.selectTask(new Page<>(page, limit), entityWrapper);
        List<ChTask> records = pageData.getRecords();
        System.out.println(JSON.toJSONString("列表数据====================" + records));
        for (ChTask chTask : records) {
            if (chTask.getTaskStatus() == 2 || (chTask.getTaskStatus() == 1 && chTask.getTaskEndTime().getTime() < System.currentTimeMillis())) {
                chTask.setIsShowExamine(1);
            } else {
                //不显示按钮
                chTask.setIsShowExamine(2);
            }
        }
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }


    @GetMapping("/selectClass")
    @SysLog("动态获取班级")
    @ResponseBody
    public RestResponse selectClass() {
        System.out.println("================================================动态获取班级================================================");
        //验证登录用户角色
        boolean b = SecurityUtils.getSubject().hasRole("班主任");
        boolean c = SecurityUtils.getSubject().hasRole("教师");
        EntityWrapper<ChClass> entityWrapper = new EntityWrapper<>();
        entityWrapper.isWhere(true);
        if (b) {
            String headTeacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            entityWrapper.andNew().eq("head_teacher_id", headTeacherId);
        }
        if (c) {
            String teacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            entityWrapper.andNew().eq("teacher_id", teacherId);
        }
        List<ChClass> chClassList = chClassService.selectClass(entityWrapper);
        System.out.println(JSON.toJSONString(chClassList));
        return RestResponse.success().setData(chClassList);
    }


    @GetMapping("/assiGnedTasks")
    @SysLog("跳转列表")
    public String add() {
        return "/ytzluser/chTask/assiGnedTasks";
    }


    @PostMapping("/classInfo")
    @SysLog("查询班级信息")
    @ResponseBody
    public LayerData<ChClass> classInfo(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        LayerData<ChClass> layerData = new LayerData<>();
        String teacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
        List<ChClass> chClassList = chTaskService.selectClassInfo(new Page<>(page, limit), teacherId);
        layerData.setData(chClassList);
        return layerData;
    }

    @GetMapping("/selectClassName")
    @SysLog("动态获取班级名称")
    @ResponseBody
    public RestResponse selectClassName() {
        System.out.println("================================================动态获取班级名称================================================");
        Map<String, Object> param = new HashMap<>();
        boolean b = SecurityUtils.getSubject().hasRole("班主任");
        boolean c = SecurityUtils.getSubject().hasRole("教师");
        if (b) {
            String headTeacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            param.put("headTeacherId", headTeacherId);
        }
        if (c) {
            String teacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            param.put("teacherId", teacherId);
        }
//        param.put("headTeacherId", 2);
        List<ChClass> chClassList = chClassService.selectClassName(param);
        return RestResponse.success().setData(chClassList);
    }


    @PostMapping("/selectStudent")
    @SysLog("通过班级号查询id")
    @ResponseBody
    public List<ChUser> selectStudent(String classId) {
        List<ChUser> chUserList = chClassService.selectStudent(classId);
        if (chUserList.size() == 0) {
            RestResponse.failure("没有该班级的学生数据");
        }
        return chUserList;
    }


    @PostMapping("/submit")
    @SysLog("立即提交")
    @ResponseBody
    public RestResponse submit(String id, String taskName, String taskType,
                               String taskStartTime, String taskEndTime, String taskDescribe) throws ParseException {
        //添加任务
        if ("".equals(id) && "".equals(taskName) && "".equals(taskType) && "".equals(taskStartTime) && "".equals(taskEndTime) && "".equals(taskDescribe)) {
            return RestResponse.failure("参数不能为空");
        }
        System.out.println("===================================学生id" + id + taskName + taskType + taskStartTime + taskEndTime + taskDescribe);
        ChTask chTask = new ChTask();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //拿到当前用户id
        String sysId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
        //生成任务表主键id
        String taskId = IdWorker.getId();
        chTask.setId(taskId);
        chTask.setSysUserId(sysId);
        chTask.setTaskName(taskName);
        chTask.setTaskDescribe(taskDescribe);
        chTask.setTaskStartTime(sdf.parse(taskStartTime));
        chTask.setTaskEndTime(sdf.parse(taskEndTime));
        chTask.setTaskType(Integer.parseInt(taskType));
        chTask.setCreateTime(new Date());
        //添加任务
        chTaskService.addTask(chTask, id);
        return RestResponse.success();
    }


    @GetMapping("/audit")
    @SysLog("跳转到不同的审核页面")
    public String audit(@RequestParam(value = "taskType") String taskType) {
        System.out.println("进入跳转");
        if ("1".equals(taskType)) {
            System.out.println("视频学习=================================" + taskType);
            return "ytzluser/chTask/audit";
        } else if ("2".equals(taskType)) {
            System.out.println("题库测验================================" + taskType);
            return "ytzluser/chTask/audit2";
        }
        return "ytzluser/chTask/audit3";
    }

    @PostMapping("/chart")
    @SysLog("通过userid查询数据,柱形统计图数据")
    @ResponseBody
    public RestResponse chart(@RequestParam(value = "userId") String userId,
                              @RequestParam(value = "taskStartTime") String taskStartTime,
                              @RequestParam(value = "taskEndTime") String taskEndTime) throws ParseException {
        if ("".equals(taskStartTime) && "".equals(taskEndTime)) {
            return RestResponse.failure("开始时间和结束时间不能为空");
        }
        if ("".equals(userId)) {
            return RestResponse.failure("用户id不能为空");
        }
        long start = Long.parseLong(taskStartTime);
        long end = Long.parseLong(taskEndTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("taskStartTime", sdf.parse(sdf.format(start)));
        map.put("taskEndTime", sdf.parse(sdf.format(end)));
        List<ChStudyVideoRecord> studyVideoRecordList = chStudyVideoRecordService.selectStudeyVideo(map);
        if (studyVideoRecordList.size() == 0) {
            return RestResponse.failure("没有该学生的学习时长数据");
        }
        System.out.println("柱形统计数据" + JSON.toJSONString(studyVideoRecordList));
        return RestResponse.success().setData(studyVideoRecordList);
    }


    @PostMapping("/chart2")
    @SysLog("通过学生id查询数据，统计折线数据")
    @ResponseBody
    public RestResponse chart2(@RequestParam(value = "userId") String userId,
                               @RequestParam(value = "taskStartTime") String taskStartTime,
                               @RequestParam(value = "taskEndTime") String taskEndTime) throws ParseException {
        if ("".equals(taskStartTime) && "".equals(taskEndTime)) {
            return RestResponse.failure("开始时间和结束时间不能为空");
        }
        if ("".equals(userId)) {
            return RestResponse.failure("用户id不能为空");
        }
        long start = Long.parseLong(taskStartTime);
        long end = Long.parseLong(taskEndTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("taskStartTime", sdf.parse(sdf.format(start)));
        map.put("taskEndTime", sdf.parse(sdf.format(end)));
        List<Date> betweenDates = DateUtil.getBetweenDates(sdf.parse(sdf.format(start)), sdf.parse(sdf.format(end)));
        map.put("list",betweenDates);
        List<UserExamDto> userExamDtoList = chUserExamService.selectStuExam(map);
        if (userExamDtoList.size() == 0) {
            return RestResponse.failure("没有该学生的试题数据");
        }
        System.out.println("折线统计数据" + JSON.toJSONString(userExamDtoList));
        return RestResponse.success().setData(userExamDtoList);
    }


    @PostMapping("/approved")
    @SysLog("审核通过")
    @ResponseBody
    public RestResponse approved(String userLinkTaskId, String taskComments) {
        if ("".equals(userLinkTaskId) && "".equals(taskComments)) {
            return RestResponse.failure("评语不能为空");
        }
        UserLinkTask userLinkTask = chUserLinkTaskService.select(userLinkTaskId);
        if (userLinkTask.getTaskStatus() == 3) {
            return RestResponse.failure("不能通过审核，该审核已通过");
        }
        System.out.println("审核通过接口");
        chUserLinkTaskService.approved(userLinkTaskId, taskComments);
        return RestResponse.success();
    }


}
